<template>
  <div class="app-container" v-loading="loading">

    <el-steps :active="active" v-if="form.organizationId == null" simple>
      <el-step title="开户" icon="el-icon-edit"></el-step>
      <el-step title="其他信息" icon="el-icon-bank-card"></el-step>
    </el-steps>
    <template v-if="active === 1">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <template v-if="organizationType === 0">
          <el-divider content-position="left">上级</el-divider>
          <el-form-item label="平台运营商" prop="parentOrganizationId">
            <el-select v-model="platformId" clearable  :remote-method="getPlatformList" @change="(val)=>getAgentList(val)" filterable remote reserve-keyword>
              <el-option v-for="item in platformList" :key="item.organizationId" :label="item.companyName" :value="item.organizationId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="代理" prop="parentOrganizationId">
            <el-select v-model="form.parentOrganizationId" clearable  :remote-method="(val)=>getAgentList(platformId,val)" filterable remote reserve-keyword>
              <el-option v-for="item in agentList" :key="item.organizationId" :label="item.companyName" :value="item.organizationId"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-divider content-position="left">企业信息</el-divider>
        <el-form-item label="营业执照" prop="businessLicensePath">
          <ImageUpload @input="handleBusinessLicense" :limit="1" v-model="form.businessLicensePath"></ImageUpload>
        </el-form-item>

        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" />
        </el-form-item>

        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" :disabled="form.signStatus === 2" placeholder="请输入统一社会信用代码" />
        </el-form-item>

        <el-form-item label="公司邮箱" prop="companyEmail">
          <el-input v-model="form.companyEmail" placeholder="请输入公司邮箱" />
        </el-form-item>

        <el-form-item label="营业执照有效期" required>
          <el-col :span="11">
            <el-form-item prop="licenseValidFrom">
              <el-date-picker clearable v-model="form.licenseValidFrom" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="licenseValidTo">
              <el-date-picker clearable v-model="form.licenseValidTo" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期结束" />
            </el-form-item>
          </el-col>
        </el-form-item>


        <el-form-item label="经营地址" prop="operateAddress">
          <el-input v-model="form.operateAddress" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入经营地址" />
        </el-form-item>


        <el-form-item label="业务简介" prop="companyProfile">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 12}" v-model="form.companyProfile" placeholder="请输入业务简介" />
        </el-form-item>

        <el-form-item label="公司内部照" prop="storefrontPhotoPath">
          <ImageUpload :limit="5" v-model="form.storefrontPhotoPath"></ImageUpload>
        </el-form-item>


        <el-divider content-position="left">法人信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="legalRepresentativeIdFront">
              <ImageUpload :limit="1" @input="handleLegalRepresentativeFront" v-model="form.legalRepresentativeIdFront"></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证背面" prop="legalRepresentativeIdBack">
              <ImageUpload @input="handleLegalRepresentativeBack" :limit="1" v-model="form.legalRepresentativeIdBack"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="法人姓名" prop="legalRepresentativeName">
              <el-input v-model="form.legalRepresentativeName" placeholder="请输入法人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="法人手机" prop="legalRepresentativePhone">
              <el-input v-model="form.legalRepresentativePhone" placeholder="请输入法人手机" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="法人身份证号" prop="legalRepresentativeIdCard">
          <el-input v-model="form.legalRepresentativeIdCard" placeholder="请输入法人身份证号" />
        </el-form-item>

        <el-form-item label="身份证有效期" required>
            <el-col :span="11">
              <el-form-item prop="legalIdNumberBeginTime">
                <el-date-picker clearable v-model="form.legalIdNumberBeginTime" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="legalIdNumberEndTime">
              <el-date-picker clearable v-model="form.legalIdNumberEndTime" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="法人身份证地址" prop="legalRepresentativeAddress">
          <el-input v-model="form.legalRepresentativeAddress" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入法人身份证地址" />
        </el-form-item>

        <el-divider content-position="left">管理员</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="管理员姓名" prop="administratorName">
              <el-input v-model="form.administratorName" placeholder="请输入管理员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员手机号" prop="administratorPhone">
              <el-input v-model="form.administratorPhone" placeholder="请输入管理员手机号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-else-if="active === 2">
      <el-form ref="form" :model="other" :rules="rules" label-width="140px">
        <el-divider content-position="left">增值税发票</el-divider>
        <el-form-item label="增值税发票类型" prop="invoiceTypeId">
          <el-checkbox-group v-model="other.invoiceTypeId">
            <el-checkbox v-for="item in invoiceTypeList"  :label="item.invoiceTypeId" :key="item.invoiceTypeId">{{item.invoiceTypeName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="行业类型" prop="industryType">
          <el-radio-group v-model="other.industryType">
            <el-radio :label="1">常规行业</el-radio>
            <el-radio :label="2">特殊商业</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
    </template>
    <div class="dialog-footer">
      <el-button v-if="active>1" @click="active--">上一步</el-button>
      <el-button v-if="form.organizationId == null" type="primary" @click="submitForm">下一步</el-button>
      <el-button v-else type="primary" @click="submitForm">提 交</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </div>
</template>
<script>

import store from "@/store";
import {listAgent} from "@/api/system/agent";
import {listPlatform} from "@/api/system/platform";
import {businessLicense, idCard} from "@/api/common";
import {listInvoiceType} from "@/api/system/InvoiceType";
import { getMerchant, addMerchant, updateMerchant, otherAdd } from "@/api/system/merchant"

export default {
  name: "merchantOperate",
  props:{
    organizationId:{
     type:String,
    },
  },
  data() {
    return{
      active:1,
      loading:false,
      platformId:null,
      agentList:[],
      platformList:[],
      invoiceTypeList:[],
      organizationType: store.getters.organizationType,
      other:{
        industryType:null,
        invoiceTypeId:[],
        organizationId:null,
      },
      form:{
        organizationId:null,
        organizationType: null,
        companyName: null,
        operateAddress: null,
        companyProfile: null,
        creditCode: null,
        companyEmail:null,
        licenseValidFrom: null,
        licenseValidTo: null,
        businessLicensePath: null,
        storefrontPhotoPath: null,
        legalRepresentativeName: null,
        legalRepresentativeIdCard: null,
        legalRepresentativeIdFront: null,
        legalRepresentativeIdBack: null,
        legalRepresentativePhone: null,
        legalRepresentativeAddress:null,
        legalIdNumberBeginTime :null,
        legalIdNumberEndTime:null,
        administratorName: null,
        administratorPhone: null,
        signStatus: null,
        extend:null,
      },
      // 表单校验
      rules: {
        organizationType: [
          { required: true, message: "组织类型 不能为空", trigger: "change" }
        ],
        companyName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        registeredAddress: [
          { required: true, message: "注册地址不能为空", trigger: "blur" }
        ],
        creditCode: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
        ],
        licenseValidFrom: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" }
        ],
        licenseValidTo: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" }
        ],
        companyEmail: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" },
          {  type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        operateAddress: [
          { required: true, message: "经营地址不能为空", trigger: "blur" }
        ],
        legalRepresentativeName: [
          { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        legalRepresentativeIdCard: [
          { required: true, message: "法人身份证号不能为空", trigger: "blur" }
        ],

        legalRepresentativeAddress: [
          { required: true, message: "法人身份证地址不能为空", trigger: "blur" }
        ],
        legalRepresentativePhone: [
          { required: true, message: "法人手机不能为空", trigger: "blur" }
        ],
        administratorName: [
          { required: true, message: "管理员姓名不能为空", trigger: "blur" }
        ],
        administratorPhone: [
          { required: true, message: "管理员手机号不能为空", trigger: "blur" }
        ],
        legalIdNumberBeginTime: [
          { required: true, message: "身份证生效日期为空", trigger: "blur" }
        ],
        legalIdNumberEndTime: [
          { required: true, message: "身份证失效日期为空", trigger: "blur" }
        ],
        legalRepresentativeIdBack: [
          { required: true, message: "请上传身份证背面", trigger: ["blur","change"] }
        ],
        legalRepresentativeIdFront: [
          { required: true, message: "请上传身份证正面", trigger: ["blur","change"] }
        ],
        businessLicensePath: [
          { required: true, message: "请上传营业执照", trigger: ["blur","change"] }
        ],
        invoiceTypeId: [
          { required: true, message: "请选择增值税发票类型", trigger: "change" }
        ],
        industryType: [
          { required: true, message: "请选择行业类型", trigger: "change" }
        ]
      }
    }
  },
  mounted() {
    if (this.organizationType === 0){
      this.getPlatformList();
    }
  },
  methods:{
    handleBusinessLicense(obj){
      if(obj){
        this.loading = true
        businessLicense({url:obj}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.companyName = words_result['单位名称'].words
            this.form.operateAddress = words_result['地址'].words
            this.form.licenseValidFrom = this.arseDate(words_result['成立日期'].words,/(\d{4})年(\d{1,2})月(\d{1,2})日/)
            this.form.licenseValidTo = this.arseDate("2999年12月31日",/(\d{4})年(\d{1,2})月(\d{1,2})日/)
            if (this.form.signStatus !== 2){
              this.form.creditCode = words_result['社会信用代码'].words
            }
            this.form.legalRepresentativeName = words_result['法人'].words
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },
    handleLegalRepresentativeFront(obj){
      if(obj){
        this.loading = true
        idCard({url:obj,idCardSide:"front"}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.legalRepresentativeName = words_result['姓名'].words
            this.form.legalRepresentativeAddress = words_result['住址'].words
            this.form.legalRepresentativeIdCard = words_result['公民身份号码'].words
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },
    handleLegalRepresentativeBack(obj){
      if(obj){
        this.loading = true
        idCard({url:obj,idCardSide:"back"}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.legalIdNumberBeginTime = this.arseDate(words_result['签发日期'].words,/(\d{4})(\d{1,2})(\d{1,2})/)
            if (words_result['失效日期'].words === "长期"){
              this.form.legalIdNumberEndTime = this.arseDate("29991231",/(\d{4})(\d{1,2})(\d{1,2})/)
            }else{
              this.form.legalIdNumberEndTime = this.arseDate(words_result['失效日期'].words,/(\d{4})(\d{1,2})(\d{1,2})/)
            }
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },

    getDetail(){
      this.loading = true
      getMerchant(this.organizationId).then(res=>{
        this.loading = false
        this.form = res.data
      }).catch(()=>{
        this.loading = false
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if ( this.active === 1){
            if (this.form.organizationId != null) {
              updateMerchant(this.form).then(response => {
                this.loading = false
                this.$modal.msgSuccess("保存成功")
                // this.other.organizationId = response.data
                // this.active++
                this.handleCancel(true)
              }).catch(()=>{
                this.loading = false
              })
            } else {
              addMerchant(this.form).then(response => {
                this.loading = false
                this.$modal.msgSuccess("保存成功")
                this.other.organizationId = response.data
                this.form.organizationId = response.data
                this.active++
                // this.handleCancel(true)
              }).catch(()=>{
                this.loading = false
              })
            }
          }else if ( this.active === 2){
            let other = this.other
            other.invoiceTypeId = other.invoiceTypeId.join(",")
            otherAdd(this.other).then(response => {
              this.loading = false
              this.$modal.msgSuccess("新增成功")
              this.handleCancel(true)
            }).catch(()=>{
              this.loading = false
            })
          }
        }
      })
    },

    handleCancel(val){
      this.$emit("cancel",val)
    },

    getPlatformList(query){
      listPlatform({companyName:query}).then(response => {
        this.platformList = response.rows
      })
    },

    getAgentList(val,query){
      listAgent({companyName:query,parentOrganizationId:val}).then(response => {
        this.agentList = response.rows
      })
    },

    arseDate(dateStr,regex) {
      const match = dateStr.match(regex);

      if (!match) return null;

      const year = parseInt(match[1]);
      // 注意：Date 对象的月份是 0-11，需要减 1
      const month = parseInt(match[2]) - 1;
      const day = parseInt(match[3]);

      return new Date(year, month, day);
    }
  },
  watch:{
    organizationId:{
      handler(val){
        if (val){
          this.getDetail()
        }
      },
      immediate:true
    },
    active:{
      handler(val){
        if (val === 2){
          listInvoiceType().then(res=>{
            this.invoiceTypeList = res.rows
          })
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
  ::v-deep .el-col{
    .el-form-item{
      width: 100%;
      .el-date-editor{
        width: 100%;
      }
    }
  }
  .line{
    text-align: center;
  }
  ::v-deep .el-radio-group{
    .el-radio{
      height: 36px;
      line-height: 35px;
    }
  }

</style>
